package ws.jdbc.concurrent.driver.sqlserver.cursor2;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.locks.ReentrantLock;
import ws.jdbc.concurrent.driver.sqlserver.CResultSetScrollableReadOnly;
import ws.jdbc.concurrent.driver.sqlserver.tds.TDSMessage;
import static ws.jdbc.concurrent.driver.sqlserver.tds.rpc.StoredProcedures.*;

/**
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class CursorScrollableReadOnly extends CResultSetScrollableReadOnly {

  public CursorScrollableReadOnly(final TDSMessage message, final Statement stmt, final ReentrantLock lock, final String sql) throws SQLException {
    super(message, stmt);

    this.lock = lock;

    try {
      lock.lock();
      tdsResultSet = message.cursorOpen(sql, SP_CURSOROPEN_SCROLLOPT_KEYSET, SP_CURSOROPEN_CCOPT_READ_ONLY);
    } finally {
      lock.unlock();
    }
  }

  @Override
  public void close() throws SQLException {
    if (tdsResultSet != null) {
      try {
        lock.lock();
        message.cursorClose(tdsResultSet.getCursor());
        tdsResultSet = null;
      } finally {
        lock.unlock();
      }
    }
  }
}
